﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;

[Serializable]
public class Vector3Data
{
    public float X;
    public float Y;
    public float Z;

    public Vector3Data() { }
    public Vector3Data(Vector3 vector)
    {
        X = vector.x;
        Y = vector.y;
        Z = vector.z;
    }
    
    public Vector3Data(float x, float y, float z)
    {
        X = x;
        Y = y;
        Z = z;
    }

    public Vector3 ToVector3()
    {
        return new Vector3(X, Y, Z);
    }
}

// 修改Player类以匹配后端的小写字段名
[Serializable]
public class Player
{
    public string playerId;     // 小写
    public string playerName;   // 小写
    public Vector3Position position;  // 修改为Vector3Position
    public Vector3Position rotation;  // 修改为Vector3Position
    public bool isConnected;    // 小写
    public string connectedTime; // 小写
    public string lastUpdateTime; // 小写
    public string prefabId;     // 小写

    // 为了兼容性，保留大写属性
    public string PlayerId => playerId;
    public string PlayerName => playerName;
    public Vector3Data Position => new Vector3Data(position.x, position.y, position.z);
    public Vector3Data Rotation => new Vector3Data(rotation.x, rotation.y, rotation.z);
    public bool IsConnected => isConnected;
    public string ConnectedTime => connectedTime;
    public string LastUpdateTime => lastUpdateTime;
    public string PrefabId => prefabId;
}

// 匹配后端position/rotation格式的类
[Serializable]
public class Vector3Position
{
    public float x;
    public float y;
    public float z;

    public Vector3Position() { }
    public Vector3Position(float x, float y, float z)
    {
        this.x = x;
        this.y = y;
        this.z = z;
    }
}

[Serializable]
public class PlayerConnectRequest
{
    public string PlayerName;
    public Vector3Data SpawnPosition;
    public string PrefabId;
}

// 修改响应类以匹配后端的小写字段名
[Serializable]
public class PlayerConnectResponse
{
    public bool success;        // 小写
    public string message;      // 小写
    public Player localPlayer;  // 小写
    public Player[] allPlayers; // 小写

    // 为了兼容性，保留大写属性
    public bool Success => success;
    public string Message => message;
    public Player LocalPlayer => localPlayer;
    public Player[] AllPlayers => allPlayers;
}

// 修复 PlayerListResponse 以匹配后端的小写字段名
[Serializable]
public class PlayerListResponse
{
    public Player[] players;      // 小写，匹配后端
    public int totalPlayers;      // 小写，匹配后端  
    public string serverTime;     // 小写，匹配后端

    // 为了兼容性，保留大写属性
    public Player[] Players => players;
    public int TotalPlayers => totalPlayers;
    public string ServerTime => serverTime;
}

[Serializable]
public class PlayerUpdateRequest
{
    public string PlayerId;
    public Vector3Data Position;
    public Vector3Data Rotation;
}

[Serializable]
public class PlayerDisconnectRequest
{
    public string PlayerId;
}

// 修复 SyncVarValue 以匹配后端格式
[Serializable]
public class SyncVarValue
{
    public string value = string.Empty;  // 小写，匹配后端
    public string type = string.Empty;   // 小写，匹配后端

    // 兼容性属性
    public string Value => value;
    public string Type => type;

    public SyncVarValue() { }

    public SyncVarValue(object val)
    {
        if (val == null)
        {
            value = "";
            type = "null";
        }
        else
        {
            value = ConvertToString(val);
            type = val.GetType().Name;
        }
    }

    public T GetValue<T>()
    {
        if (string.IsNullOrEmpty(value))
            return default(T);

        try
        {
            if (typeof(T) == typeof(string))
                return (T)(object)value;
            else if (typeof(T) == typeof(int))
                return (T)(object)int.Parse(value);
            else if (typeof(T) == typeof(float))
                return (T)(object)float.Parse(value);
            else if (typeof(T) == typeof(bool))
                return (T)(object)bool.Parse(value);
            else if (typeof(T) == typeof(Vector3))
            {
                var parts = value.Split(',');
                if (parts.Length == 3)
                {
                    var vector = new Vector3(
                        float.Parse(parts[0]),
                        float.Parse(parts[1]),
                        float.Parse(parts[2])
                    );
                    return (T)(object)vector;
                }
            }
            else if (typeof(T) == typeof(Vector3Data))
            {
                var parts = value.Split(',');
                if (parts.Length == 3)
                {
                    return (T)(object)new Vector3Data(
                        float.Parse(parts[0]),
                        float.Parse(parts[1]),
                        float.Parse(parts[2])
                    );
                }
            }
        }
        catch (Exception ex)
        {
            Debug.LogError($"SyncVar值转换失败: {ex.Message}");
        }

        return default(T);
    }

    private string ConvertToString(object val)
    {
        if (val is Vector3 vector3)
            return $"{vector3.x},{vector3.y},{vector3.z}";
        else if (val is Vector3Data vector3Data)
            return $"{vector3Data.X},{vector3Data.Y},{vector3Data.Z}";

        return val?.ToString() ?? "";
    }
}

// 可序列化的 SyncVar 条目
[Serializable]
public class SyncVarEntry
{
    public string name = string.Empty;  // 改为 "name" 匹配后端
    public string value = string.Empty; // 直接使用字符串值
    public string type = string.Empty;  // 类型字符串

    public SyncVarEntry() { }

    public SyncVarEntry(string fieldName, SyncVarValue syncVarValue)
    {
        name = fieldName;
        value = syncVarValue.value;  // 直接使用SyncVarValue的value字符串
        type = syncVarValue.type;    // 直接使用SyncVarValue的type字符串
    }
}

// 修复 SyncVarUpdateRequest 以匹配后端期望的格式
[Serializable]
public class SyncVarUpdateRequest
{
    public string objectId = string.Empty;  // 小写，匹配后端
    public string playerId = string.Empty;  // 小写，匹配后端
    public SyncVarEntry[] variables = new SyncVarEntry[0];  // 数组代替Dictionary
    
    // 兼容性属性
    public string ObjectId => objectId;
    public string PlayerId => playerId;
    
    // 将Dictionary转换为数组的辅助方法
    public void SetVariables(Dictionary<string, SyncVarValue> dict)
    {
        if (dict == null)
        {
            variables = new SyncVarEntry[0];
            return;
        }
        
        variables = new SyncVarEntry[dict.Count];
        int index = 0;
        foreach (var kvp in dict)
        {
            variables[index] = new SyncVarEntry(kvp.Key, kvp.Value);
            index++;
        }
    }

    // 将数组转换为Dictionary的辅助方法
    public Dictionary<string, SyncVarValue> GetVariablesDictionary()
    {
        var dict = new Dictionary<string, SyncVarValue>();
        if (variables != null)
        {
            foreach (var entry in variables)
            {
                if (!string.IsNullOrEmpty(entry.name) && !string.IsNullOrEmpty(entry.value))
                {
                    var syncVarValue = new SyncVarValue();
                    syncVarValue.value = entry.value;
                    syncVarValue.type = entry.type;
                    dict[entry.name] = syncVarValue;
                }
            }
        }
        return dict;
    }
}

// 包装器类 - 根据后端期望的 request 字段
[Serializable]
public class SyncVarUpdateWrapper
{
    public SyncVarUpdateRequest request;
    
    public SyncVarUpdateWrapper() { }
    
    public SyncVarUpdateWrapper(SyncVarUpdateRequest req)
    {
        request = req;
    }
}

// 可序列化的对象变量条目
[Serializable]
public class ObjectVariableEntry
{
    public string objectId = string.Empty;
    public SyncVarEntry[] variables = new SyncVarEntry[0];

    public ObjectVariableEntry() { }

    public ObjectVariableEntry(string id, Dictionary<string, SyncVarValue> vars)
    {
        objectId = id;
        if (vars != null)
        {
            variables = new SyncVarEntry[vars.Count];
            int index = 0;
            foreach (var kvp in vars)
            {
                variables[index] = new SyncVarEntry(kvp.Key, kvp.Value);
                index++;
            }
        }
    }

    public Dictionary<string, SyncVarValue> GetVariablesDictionary()
    {
        var dict = new Dictionary<string, SyncVarValue>();
        if (variables != null)
        {
            foreach (var entry in variables)
            {
                if (!string.IsNullOrEmpty(entry.name) && !string.IsNullOrEmpty(entry.value))
                {
                    var syncVarValue = new SyncVarValue();
                    syncVarValue.value = entry.value;
                    syncVarValue.type = entry.type;
                    dict[entry.name] = syncVarValue;
                }
            }
        }
        return dict;
    }
}

// 修复 SyncVarResponse 以支持 JsonUtility 序列化
[Serializable]
public class SyncVarResponse
{
    public bool success;  // 小写，匹配后端
    public string message = string.Empty;  // 小写，匹配后端
    public ObjectVariableEntry[] allVariables = new ObjectVariableEntry[0];  // 数组代替Dictionary

    // 兼容性属性
    public bool Success => success;
    public string Message => message;

    // 将数组转换为Dictionary的辅助方法
    public Dictionary<string, Dictionary<string, SyncVarValue>> GetAllVariablesDictionary()
    {
        var dict = new Dictionary<string, Dictionary<string, SyncVarValue>>();
        if (allVariables != null)
        {
            foreach (var entry in allVariables)
            {
                if (!string.IsNullOrEmpty(entry.objectId))
                {
                    dict[entry.objectId] = entry.GetVariablesDictionary();
                }
            }
        }
        return dict;
    }
}

public class NetworkManager : MonoSingleton<NetworkManager>
{
    [Header("网络设置")]
    public string serverUrl = "http://192.168.101.111:5000";

    [Header("玩家设置")]
    public string playerName = "玩家";
    [Tooltip("玩家预制体，必须包含NetworkBehaviour组件")]
    public GameObject playerPrefab;

    [Header("按键设置")]
    public KeyCode connectKey = KeyCode.C;
    public KeyCode disconnectKey = KeyCode.X;

    [Header("调试")]
    public bool showDebugInfo = true;

    // 状态变量
    public bool isConnected = false; // 改为public
    private string localPlayerId;
    private Player localPlayerData;

    // 网络对象管理
    private Dictionary<string, GameObject> playerObjects = new Dictionary<string, GameObject>();
    private Dictionary<string, NetworkBehaviour> networkBehaviours = new Dictionary<string, NetworkBehaviour>();

    // UI状态
    private string connectionStatus = "未连接";
    private int connectedPlayersCount = 0;


    void Update()
    {
        // 连接按键
        if (Input.GetKeyDown(connectKey) && !isConnected)
        {
            StartCoroutine(ConnectToServer());
        }

        // 断开连接按键
        if (Input.GetKeyDown(disconnectKey) && isConnected)
        {
            StartCoroutine(DisconnectFromServer());
        }

        // 测试按键 - 按T键测试不同的端点
        if (Input.GetKeyDown(KeyCode.T))
        {
            StartCoroutine(TestDifferentEndpoints());
        }

        // 按L键测试玩家列表API
        if (Input.GetKeyDown(KeyCode.L))
        {
            StartCoroutine(TestPlayerListAPI());
        }

        // 如果已连接，定期更新玩家列表
        if (isConnected)
        {
            // 每秒更新一次玩家列表
            if (Time.time % 1f < Time.deltaTime)
            {
                StartCoroutine(UpdatePlayerList());
            }
        }
    }

    // 专门测试玩家列表API
    IEnumerator TestPlayerListAPI()
    {
        Debug.Log("=== 专门测试玩家列表API ===");

        string listUrl = $"{serverUrl}/api/Player/list";
        Debug.Log($"测试URL: {listUrl}");

        using (UnityWebRequest request = UnityWebRequest.Get(listUrl))
        {
            yield return request.SendWebRequest();

            Debug.Log($"响应码: {request.responseCode}");
            Debug.Log($"请求结果: {request.result}");
            Debug.Log($"原始响应: {request.downloadHandler.text}");

            if (request.result == UnityWebRequest.Result.Success)
            {
                string responseText = request.downloadHandler.text;

                try
                {
                    var response = JsonUtility.FromJson<PlayerListResponse>(responseText);
                    Debug.Log("=== JSON解析结果 ===");
                    Debug.Log($"response != null: {response != null}");
                    if (response != null)
                    {
                        Debug.Log($"players数组: {response.players?.Length ?? -1}");
                        Debug.Log($"totalPlayers: {response.totalPlayers}");
                        Debug.Log($"serverTime: {response.serverTime}");

                        // 测试兼容性属性
                        Debug.Log($"Players属性: {response.Players?.Length ?? -1}");
                        Debug.Log($"TotalPlayers属性: {response.TotalPlayers}");
                        Debug.Log($"ServerTime属性: {response.ServerTime}");

                        if (response.players != null)
                        {
                            for (int i = 0; i < response.players.Length; i++)
                            {
                                var player = response.players[i];
                                Debug.Log($"玩家[{i}]: {player?.playerName} (ID: {player?.playerId})");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.LogError($"JSON解析失败: {ex.Message}");
                }
            }
        }
    }

    // 测试不同的端点
    IEnumerator TestDifferentEndpoints()
    {
        Debug.Log("=== 测试不同的API端点 ===");

        string[] testEndpoints = {
            $"{serverUrl}/api/Player/connect",
            $"{serverUrl}/api/Player/list",
            $"{serverUrl}/api/Player/server-status"
        };

        foreach (string endpoint in testEndpoints)
        {
            Debug.Log($"测试端点: {endpoint}");

            // 测试 GET 请求
            using (UnityWebRequest request = UnityWebRequest.Get(endpoint))
            {
                yield return request.SendWebRequest();
                Debug.Log($"GET {endpoint}: {request.result} - {request.responseCode}");
            }

            yield return new WaitForSeconds(0.1f);
        }
    }

    // 连接到服务器
    IEnumerator ConnectToServer()
    {
        connectionStatus = "正在连接...";
        Debug.Log("尝试连接服务器...");

        var connectRequest = new PlayerConnectRequest
        {
            PlayerName = playerName,
            SpawnPosition = new Vector3Data(Vector3.zero),
            PrefabId = playerPrefab != null ? playerPrefab.name : "DefaultPlayer"
        };

        string jsonData = JsonUtility.ToJson(connectRequest);
        Debug.Log($"发送的JSON数据: {jsonData}");

        // 使用确切的API路径
        string connectUrl = $"{serverUrl}/api/Player/connect";
        Debug.Log($"尝试连接到: {connectUrl}");

        using (UnityWebRequest request = new UnityWebRequest(connectUrl, "POST"))
        {
            byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonData);
            request.uploadHandler = new UploadHandlerRaw(bodyRaw);
            request.downloadHandler = new DownloadHandlerBuffer();
            request.SetRequestHeader("Content-Type", "application/json");
            request.SetRequestHeader("Accept", "application/json");

            yield return request.SendWebRequest();

            Debug.Log($"响应码: {request.responseCode}");
            Debug.Log($"响应内容: {request.downloadHandler.text}");

            if (request.result == UnityWebRequest.Result.Success)
            {
                try
                {
                    // 现在字段名匹配了，应该能正确解析
                    var response = JsonUtility.FromJson<PlayerConnectResponse>(request.downloadHandler.text);

                    Debug.Log($"JSON解析结果:");
                    Debug.Log($"Success: {response?.Success}");
                    Debug.Log($"Message: {response?.Message}");
                    Debug.Log($"LocalPlayer: {(response?.LocalPlayer != null ? "存在" : "null")}");
                    Debug.Log($"AllPlayers: {(response?.AllPlayers != null ? response.AllPlayers.Length.ToString() : "null")}");

                    if (response != null && response.Success)
                    {
                        if (response.LocalPlayer != null)
                        {
                            isConnected = true;
                            localPlayerId = response.LocalPlayer.PlayerId;
                            localPlayerData = response.LocalPlayer;
                            connectionStatus = "已连接";

                            Debug.Log($"连接成功！");
                            Debug.Log($"玩家ID: {localPlayerId}");
                            Debug.Log($"玩家名: {localPlayerData.PlayerName}");

                            // 生成所有玩家（包括自己）
                            if (response.AllPlayers != null && response.AllPlayers.Length > 0)
                            {
                                Debug.Log($"生成 {response.AllPlayers.Length} 个玩家");
                                SpawnAllPlayers(response.AllPlayers);
                            }
                            else
                            {
                                Debug.LogWarning("AllPlayers 为空或null");
                            }

                            // 开始接收SyncVar更新
                            StartCoroutine(ReceiveSyncVarUpdates());
                        }
                        else
                        {
                            connectionStatus = "连接失败";
                            Debug.LogError("LocalPlayer 为 null");
                        }
                    }
                    else
                    {
                        connectionStatus = "连接失败";
                        Debug.LogError($"连接失败: {response?.Message ?? "无效响应"}");
                    }
                }
                catch (Exception ex)
                {
                    connectionStatus = "连接失败";
                    Debug.LogError($"JSON解析失败: {ex.Message}");
                    Debug.LogError($"原始响应: {request.downloadHandler.text}");
                }
            }
            else
            {
                connectionStatus = "连接失败";
                Debug.LogError($"请求失败: {request.error} - 响应码: {request.responseCode}");
                Debug.LogError($"响应内容: {request.downloadHandler.text}");
            }
        }
    }

    // 断开连接
    IEnumerator DisconnectFromServer()
    {
        if (!isConnected) yield break;

        connectionStatus = "正在断开连接...";
        Debug.Log("断开连接...");

        var disconnectRequest = new PlayerDisconnectRequest { PlayerId = localPlayerId };
        string jsonData = JsonUtility.ToJson(disconnectRequest);

        using (UnityWebRequest request = new UnityWebRequest($"{serverUrl}/api/Player/disconnect", "POST"))
        {
            byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonData);
            request.uploadHandler = new UploadHandlerRaw(bodyRaw);
            request.downloadHandler = new DownloadHandlerBuffer();
            request.SetRequestHeader("Content-Type", "application/json");

            yield return request.SendWebRequest();
            PerformLocalDisconnect();
        }
    }

    void PerformLocalDisconnect()
    {
        isConnected = false;
        connectionStatus = "未连接";
        localPlayerId = null;
        localPlayerData = null;

        // 清理所有玩家对象
        foreach (var playerObj in playerObjects.Values)
        {
            if (playerObj != null)
                Destroy(playerObj);
        }

        playerObjects.Clear();
        networkBehaviours.Clear();
        connectedPlayersCount = 0;

        Debug.Log("已断开连接");
    }

    // 修复的更新玩家列表方法
    IEnumerator UpdatePlayerList()
    {
        string listUrl = $"{serverUrl}/api/Player/list";

        using (UnityWebRequest request = UnityWebRequest.Get(listUrl))
        {
            yield return request.SendWebRequest();

            if (request.result == UnityWebRequest.Result.Success)
            {
                string responseText = request.downloadHandler.text;

                if (string.IsNullOrEmpty(responseText))
                {
                    Debug.LogWarning("玩家列表响应为空");
                    yield break;
                }

                try
                {
                    var response = JsonUtility.FromJson<PlayerListResponse>(responseText);

                    if (response == null)
                    {
                        Debug.LogError("玩家列表JSON解析失败！返回null对象");
                        yield break;
                    }

                    // 现在应该能正确获取数据
                    connectedPlayersCount = response.TotalPlayers;

                    if (response.Players != null)
                    {
                        UpdatePlayerObjects(response.Players);
                    }
                    else
                    {
                        Debug.LogWarning("玩家数组为null，使用空数组");
                        UpdatePlayerObjects(new Player[0]);
                    }
                }
                catch (Exception ex)
                {
                    Debug.LogError($"玩家列表JSON解析异常: {ex.Message}");
                    Debug.LogError($"尝试解析的内容: {responseText}");
                }
            }
            else
            {
                Debug.LogError($"获取玩家列表失败: {request.error}");
            }
        }
    }

    // 生成所有玩家
    void SpawnAllPlayers(Player[] players)
    {
        if (players == null)
        {
            Debug.LogError("SpawnAllPlayers: players数组为null");
            return;
        }

        Debug.Log($"SpawnAllPlayers: 开始生成 {players.Length} 个玩家");

        foreach (var player in players)
        {
            if (player != null)
            {
                SpawnPlayer(player);
            }
            else
            {
                Debug.LogWarning("发现null玩家对象，跳过");
            }
        }
    }

    // 生成单个玩家
    void SpawnPlayer(Player playerData)
    {
        if (playerData == null)
        {
            Debug.LogError("SpawnPlayer: playerData为null");
            return;
        }

        if (string.IsNullOrEmpty(playerData.PlayerId))
        {
            Debug.LogError($"SpawnPlayer: PlayerId为空 (playerName: {playerData.PlayerName})");
            return;
        }

        if (playerObjects.ContainsKey(playerData.PlayerId))
        {
            Debug.LogWarning($"玩家 {playerData.PlayerId} 已存在，跳过生成");
            return;
        }

        if (playerPrefab == null)
        {
            Debug.LogError("玩家预制体未设置！无法生成玩家");
            return;
        }

        // 检查并修复位置数据
        if (playerData.position == null)
        {
            Debug.LogWarning($"玩家 {playerData.PlayerId} 位置为null，使用默认位置");
            playerData.position = new Vector3Position(0, 0, 0);
        }

        if (playerData.rotation == null)
        {
            Debug.LogWarning($"玩家 {playerData.PlayerId} 旋转为null，使用默认旋转");
            playerData.rotation = new Vector3Position(0, 0, 0);
        }

        // 解析位置和旋转
        Vector3 spawnPosition = playerData.Position.ToVector3();
        Vector3 spawnRotation = playerData.Rotation.ToVector3();

        // 实例化玩家预制体
        GameObject playerObj = Instantiate(playerPrefab, spawnPosition, Quaternion.Euler(spawnRotation));
        playerObj.name = $"Player_{playerData.PlayerName}_{playerData.PlayerId[..8]}" ;

        // 获取NetworkBehaviour组件
        var networkBehaviour = playerObj.GetComponent<NetworkBehaviour>();
        if (networkBehaviour == null)
        {
            Debug.LogError($"玩家预制体 {playerPrefab.name} 缺少NetworkBehaviour组件！");
            Destroy(playerObj);
            return;
        }

        // 判断是否为本地玩家
        bool isLocalPlayer = playerData.PlayerId == localPlayerId;

        // 设置网络身份
        networkBehaviour.SetNetworkIdentity(playerData.PlayerId, playerData.PlayerId, isLocalPlayer);

        // 注册玩家对象
        playerObjects[playerData.PlayerId] = playerObj;

        if (showDebugInfo)
        {
            Debug.Log($"生成玩家: {playerData.PlayerName} (ID: {playerData.PlayerId[..8]}, 本地: {isLocalPlayer})");
        }

        // 如果有PlayerInfo组件，设置基本信息
        if (networkBehaviour is PlayerInfo playerInfo)
        {
            playerInfo.playerName = playerData.PlayerName;
            playerInfo.targetPosition = spawnPosition;
        }
    }

    // 更新玩家对象
    void UpdatePlayerObjects(Player[] currentPlayers)
    {
        if (currentPlayers == null)
        {
            Debug.LogError("UpdatePlayerObjects: currentPlayers为null！");
            return;
        }

        try
        {
            // 过滤有效玩家
            var validPlayers = currentPlayers.Where(p => p != null && !string.IsNullOrEmpty(p.PlayerId)).ToArray();
            var currentPlayerIds = new HashSet<string>(validPlayers.Select(p => p.PlayerId));

            // 移除已断开连接的玩家
            var playersToRemove = playerObjects.Keys.Where(id => !currentPlayerIds.Contains(id)).ToList();
            foreach (var playerId in playersToRemove)
            {
                if (playerObjects.TryGetValue(playerId, out var playerObj) && playerObj != null)
                {
                    Debug.Log($"移除断开连接的玩家: {playerId[..8]}");
                    Destroy(playerObj);
                }
                playerObjects.Remove(playerId);
                networkBehaviours.Remove(playerId);
            }

            // 添加新玩家
            foreach (var player in validPlayers)
            {
                if (!playerObjects.ContainsKey(player.PlayerId))
                {
                    Debug.Log($"发现新玩家: {player.PlayerName} (ID: {player.PlayerId})");
                    SpawnPlayer(player);
                }
            }

        }
        catch (Exception ex)
        {
            Debug.LogError($"UpdatePlayerObjects异常: {ex.Message}");
            Debug.LogError($"堆栈: {ex.StackTrace}");
        }
    }

    // NetworkBehaviour注册管理
    public void RegisterNetworkBehaviour(NetworkBehaviour behaviour)
    {
        string networkId = behaviour.GetNetworkId();
        if (!string.IsNullOrEmpty(networkId))
        {
            networkBehaviours[networkId] = behaviour;
            if (showDebugInfo)
                Debug.Log($"注册NetworkBehaviour: {networkId[..8]} ({behaviour.GetType().Name})");
        }
    }

    public void UnregisterNetworkBehaviour(NetworkBehaviour behaviour)
    {
        string networkId = behaviour.GetNetworkId();
        if (!string.IsNullOrEmpty(networkId))
        {
            networkBehaviours.Remove(networkId);
            if (showDebugInfo)
                Debug.Log($"注销NetworkBehaviour: {networkId[..8]}");
        }
    }

    // 修复的 SyncVar更新发送
    public void SendSyncVarUpdate(string objectId, Dictionary<string, SyncVarValue> updates)
    {
        if (!isConnected)
        {
            Debug.LogWarning("未连接服务器，无法发送SyncVar更新");
            return;
        }

        StartCoroutine(SendSyncVarUpdateCoroutine(objectId, updates));
    }

    IEnumerator SendSyncVarUpdateCoroutine(string objectId, Dictionary<string, SyncVarValue> updates)
    {
        // 验证参数
        if (string.IsNullOrEmpty(objectId))
        {
            Debug.LogError("SendSyncVarUpdate: objectId不能为空");
            yield break;
        }
        
        if (string.IsNullOrEmpty(localPlayerId))
        {
            Debug.LogError("SendSyncVarUpdate: localPlayerId不能为空");
            yield break;
        }

        // 创建请求对象
        var syncVarRequest = new SyncVarUpdateRequest
        {
            objectId = objectId,
            playerId = localPlayerId
        };
        
        // 使用SetVariables方法转换Dictionary为数组
        syncVarRequest.SetVariables(updates);

        // 直接序列化请求，不使用包装器 (匹配后端期望格式)
        string jsonData = JsonUtility.ToJson(syncVarRequest);

        // 添加详细的调试信息
        Debug.Log($"=== 发送SyncVar更新 (匹配后端格式) ===");
        Debug.Log($"ObjectId: '{objectId}' (长度: {objectId?.Length ?? 0})");
        Debug.Log($"PlayerId: '{localPlayerId}' (长度: {localPlayerId?.Length ?? 0})");
        Debug.Log($"Variables Count: {updates.Count}");
        Debug.Log($"匹配后端的JSON: {jsonData}");

        using (UnityWebRequest webRequest = new UnityWebRequest($"{serverUrl}/api/SyncVar/update", "POST"))
        {
            byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonData);
            webRequest.uploadHandler = new UploadHandlerRaw(bodyRaw);
            webRequest.downloadHandler = new DownloadHandlerBuffer();
            webRequest.SetRequestHeader("Content-Type", "application/json");

            yield return webRequest.SendWebRequest();

            if (webRequest.result == UnityWebRequest.Result.Success)
            {
                Debug.Log($"SyncVar更新成功: {objectId[..Math.Min(8, objectId.Length)]} ({updates.Count} 个变量)");
                Debug.Log($"服务器响应: {webRequest.downloadHandler.text}");
            }
            else
            {
                Debug.LogError($"SyncVar更新失败: {webRequest.error}");
                Debug.LogError($"响应码: {webRequest.responseCode}");
                Debug.LogError($"响应内容: {webRequest.downloadHandler.text}");
                Debug.LogError($"发送的数据: {jsonData}");
                
                // 调试：显示包装器格式以供比较
                Debug.Log("包装器格式对比:");
                var requestWrapper = new SyncVarUpdateWrapper(syncVarRequest);
                string wrappedJson = JsonUtility.ToJson(requestWrapper);
                Debug.Log($"包装器格式JSON: {wrappedJson}");
            }
        }
    }

    // 接收SyncVar更新
    IEnumerator ReceiveSyncVarUpdates()
    {
        Debug.Log("开始接收SyncVar更新循环");
        
        while (isConnected)
        {
            yield return new WaitForSeconds(0.1f); // 每100ms检查一次更新

            using (UnityWebRequest request = UnityWebRequest.Get($"{serverUrl}/api/SyncVar/variables"))
            {
                yield return request.SendWebRequest();

                // 增强调试信息
                if (request.result == UnityWebRequest.Result.Success)
                {
                    string responseText = request.downloadHandler.text;
                    
                    // 只在有实际内容时记录日志，避免空响应刷屏
                    if (!string.IsNullOrEmpty(responseText) && responseText != "{}")
                    {
                        Debug.Log($"收到SyncVar响应: {responseText}");
                        ParseAndApplySyncVarUpdates(responseText);
                    }
                }
                else
                {
                    Debug.LogError($"接收SyncVar更新失败: {request.error}");
                    Debug.LogError($"响应码: {request.responseCode}");
                    Debug.LogError($"URL: {request.url}");
                }
            }
        }
        
        Debug.Log("SyncVar更新接收循环已停止");
    }

    void ParseAndApplySyncVarUpdates(string jsonResponse)
    {
        if (string.IsNullOrEmpty(jsonResponse) || jsonResponse == "{}")
            return;

        try
        {
            Debug.Log($"尝试解析SyncVar响应: {jsonResponse}");
            
            // 首先尝试解析为标准的SyncVarResponse格式
            var response = JsonUtility.FromJson<SyncVarResponse>(jsonResponse);

            // 如果标准格式解析失败，尝试解析为直接的Dictionary格式
            if (response?.Success != true || response?.allVariables?.Length == 0)
            {
                Debug.Log("解析为直接Dictionary格式");
                
                // 手动解析后端直接返回的Dictionary格式
                var allVariables = ParseDirectDictionaryFormat(jsonResponse);
                
                if (allVariables.Count > 0)
                {
                    Debug.Log($"成功解析直接Dictionary格式，包含 {allVariables.Count} 个对象");
                    ApplyParsedSyncVarUpdates(allVariables);
                    return;
                }
            }
            else
            {
                // 使用标准格式解析结果
                var allVariables = response.GetAllVariablesDictionary();
                ApplyParsedSyncVarUpdates(allVariables);
            }
        }
        catch (Exception ex)
        {
            Debug.LogError($"解析SyncVar更新失败: {ex.Message}");
            Debug.LogError($"堆栈跟踪: {ex.StackTrace}");
            Debug.LogError($"原始响应: {jsonResponse}");
        }
    }

    // 解析后端直接返回的Dictionary格式
    [Serializable]
    public class PlayerVariablesWrapper
    {
        // 由于JsonUtility的限制，我们需要一个更简单的方法
    }

    // 简化的直接解析方法
    Dictionary<string, Dictionary<string, SyncVarValue>> ParseDirectDictionaryFormat(string jsonResponse)
    {
        var result = new Dictionary<string, Dictionary<string, SyncVarValue>>();
        
        try
        {
            // 移除外层大括号
            string content = jsonResponse.Trim();
            if (content.StartsWith("{") && content.EndsWith("}"))
            {
                content = content.Substring(1, content.Length - 2);
            }
            
            var playerIds = ExtractPlayerIds(jsonResponse);
            
            foreach (string playerId in playerIds)
            {
                
                var variables = ExtractPlayerVariables(jsonResponse, playerId);
                if (variables.Count > 0)
                {
                    result[playerId] = variables;
                }
            }
            
        }
        catch (Exception ex)
        {
            Debug.LogError($"直接Dictionary格式解析失败: {ex.Message}");
        }
        
        return result;
    }

    // 提取玩家ID列表
    List<string> ExtractPlayerIds(string jsonResponse)
    {
        var playerIds = new List<string>();
        
        try
        {
            // 查找所有类似 "player_xxxxx": 的模式
            int startIndex = 0;
            while (true)
            {
                int playerIndex = jsonResponse.IndexOf("\"player_", startIndex);
                if (playerIndex == -1) break;
                
                int endQuoteIndex = jsonResponse.IndexOf("\":", playerIndex + 1);
                if (endQuoteIndex == -1) break;
                
                string playerId = jsonResponse.Substring(playerIndex + 1, endQuoteIndex - playerIndex - 1);
                playerIds.Add(playerId);
                
                startIndex = endQuoteIndex + 1;
            }
        }
        catch (Exception ex)
        {
            Debug.LogError($"提取玩家ID失败: {ex.Message}");
        }
        
        Debug.Log($"提取到 {playerIds.Count} 个玩家ID: {string.Join(", ", playerIds)}");
        return playerIds;
    }

    // 提取指定玩家的变量
    Dictionary<string, SyncVarValue> ExtractPlayerVariables(string jsonResponse, string playerId)
    {
        var variables = new Dictionary<string, SyncVarValue>();
        
        try
        {
            // 查找该玩家的数据段
            string playerPattern = $"\"{playerId}\":";
            int playerStart = jsonResponse.IndexOf(playerPattern);
            if (playerStart == -1) return variables;
            
            // 找到该玩家数据的开始位置
            int dataStart = jsonResponse.IndexOf("{", playerStart);
            if (dataStart == -1) return variables;
            
            // 找到该玩家数据的结束位置（匹配的大括号）
            int braceCount = 0;
            int dataEnd = dataStart;
            for (int i = dataStart; i < jsonResponse.Length; i++)
            {
                if (jsonResponse[i] == '{') braceCount++;
                else if (jsonResponse[i] == '}') braceCount--;
                
                if (braceCount == 0)
                {
                    dataEnd = i;
                    break;
                }
            }
            
            // 提取该玩家的数据段
            string playerData = jsonResponse.Substring(dataStart, dataEnd - dataStart + 1);
            Debug.Log($"玩家 {playerId} 的数据段: {playerData}");
            
            // 解析变量
            variables = ExtractVariablesFromPlayerData(playerData);
        }
        catch (Exception ex)
        {
            Debug.LogError($"提取玩家 {playerId} 变量失败: {ex.Message}");
        }
        
        return variables;
    }

    // 从玩家数据段中提取变量
    Dictionary<string, SyncVarValue> ExtractVariablesFromPlayerData(string playerData)
    {
        var variables = new Dictionary<string, SyncVarValue>();
        
        try
        {
            // 查找所有的变量：类似 "targetPosition":{"value":"x,y,z","type":"Vector3"}
            int startIndex = 1; // 跳过开始的大括号
            
            while (startIndex < playerData.Length - 1)
            {
                // 查找变量名
                int nameStart = playerData.IndexOf("\"", startIndex);
                if (nameStart == -1) break;
                
                int nameEnd = playerData.IndexOf("\":", nameStart + 1);
                if (nameEnd == -1) break;
                
                string varName = playerData.Substring(nameStart + 1, nameEnd - nameStart - 1);
                
                // 查找该变量的值对象
                int valueStart = playerData.IndexOf("{", nameEnd);
                if (valueStart == -1) break;
                
                // 找到值对象的结束
                int braceCount = 0;
                int valueEnd = valueStart;
                for (int i = valueStart; i < playerData.Length; i++)
                {
                    if (playerData[i] == '{') braceCount++;
                    else if (playerData[i] == '}') braceCount--;
                    
                    if (braceCount == 0)
                    {
                        valueEnd = i;
                        break;
                    }
                }
                
                // 提取值对象
                string valueObject = playerData.Substring(valueStart, valueEnd - valueStart + 1);
                
                // 解析值对象中的value和type
                var syncVarValue = ParseSyncVarValueObject(valueObject);
                if (syncVarValue != null)
                {
                    variables[varName] = syncVarValue;
                    Debug.Log($"提取变量: {varName} = {syncVarValue.value} ({syncVarValue.type})");
                }
                
                startIndex = valueEnd + 1;
            }
        }
        catch (Exception ex)
        {
            Debug.LogError($"从玩家数据段提取变量失败: {ex.Message}");
        }
        
        return variables;
    }

    // 解析SyncVarValue对象
    SyncVarValue ParseSyncVarValueObject(string valueObject)
    {
        try
        {
            // 使用JsonUtility解析单个SyncVarValue对象
            var syncVarValue = JsonUtility.FromJson<SyncVarValue>(valueObject);
            return syncVarValue;
        }
        catch (Exception ex)
        {
            Debug.LogError($"解析SyncVarValue对象失败: {ex.Message}, 对象: {valueObject}");
            return null;
        }
    }

    // 应用解析后的SyncVar更新
    void ApplyParsedSyncVarUpdates(Dictionary<string, Dictionary<string, SyncVarValue>> allVariables)
    {
        Debug.Log($"开始应用解析后的变量更新，包含 {allVariables.Count} 个对象");

        foreach (var objectData in allVariables)
        {
            string objectId = objectData.Key;
            var variables = objectData.Value;
            
            Debug.Log($"处理对象 {objectId} 的 {variables.Count} 个变量");

            // 查找对应的NetworkBehaviour
            if (networkBehaviours.TryGetValue(objectId, out var networkBehaviour))
            {
                Debug.Log($"找到NetworkBehaviour: {networkBehaviour.gameObject.name} (IsLocal: {networkBehaviour.IsLocalPlayer()})");
                
                foreach (var variable in variables)
                {
                    string fieldName = variable.Key;
                    var syncVarValue = variable.Value;
                    
                    Debug.Log($"应用SyncVar更新: {fieldName} = {syncVarValue.value} (类型: {syncVarValue.type})");
                    networkBehaviour.ApplySyncVarUpdate(fieldName, syncVarValue);
                }
            }
            else
            {
                Debug.LogWarning($"未找到对象ID为 {objectId} 的NetworkBehaviour");
                Debug.Log($"当前注册的NetworkBehaviour对象:");
                foreach (var kvp in networkBehaviours)
                {
                    Debug.Log($"  - {kvp.Key}: {kvp.Value.gameObject.name}");
                }
            }
        }
    }
}